/*
 * @Author: 胡海
 * @Date: 2020-04-02 21:13:04
 * @LastEditors: 胡海
 * @LastEditTime: 2020-04-06 21:28:09
 * @Description: 
 */
// pages/supermarket/supermarket.js
const db = wx.cloud.database()
Page({
  data: {
    flag: 0,
    currentTab: 0,
    goods: [{
        pic: '/images/market/cy1.png',
        name: '简约楼梯个性创意灯',
        price: 566,
        buyNum: 0,
        id: 'hhhhg'
      },
      {
        pic: '/images/market/dd1.png',
        name: '北欧吊灯创意个性吊灯',
        price: 888,
        buyNum: 0,
        id: 2
      }
    ]
  },
  onLoad: function (options) {
    //进来的时候传0
    this._getCpList(0)
  },
  switchNav: function (e) { // 切换
    var page = this;
    var id = e.target.id;
    if (this.data.currentTab == id) {
      return false;
    } else {
      page.setData({
        currentTab: id
      });
    }
    page.setData({
      flag: id
    });
    let type = +id
    this._getCpList(type)
  },
  onSearch(event) { // 搜索
    let keyword = event.detail.keyword
    this._keyCpList(keyword)
  },
  _keyCpList(keyword) { // 关键字搜索
    let w = {}
    if (keyword.trim() != '') {
      w = {
        name: new db.RegExp({
          regexp: keyword,
          options: 'i'
        })
      }
    }
    db.collection('cp')
      .where(w)
      .get()
      .then((res) => {
        let data = res.data.map(item => {
          return {
            ...item,
            pic: item.img
          }
        })
        this.setData({
          goods: data
        })
      })
  },
  _getCpList(type) { // 搜索产品
    db.collection('cp')
      .where({
        type
      })
      .get()
      .then((res) => {
        let data = res.data.map(item => {
          return {
            ...item,
            pic: item.img
          }
        })
        this.setData({
          goods: data
        })
      })
  },
  loadGoods: function () {
    var goods = wx.getStorageSync('goods');
    var result = [];
    for (var i = 0; i < goods.length; i++) {
      var good = goods[i];
      var type = good.type;
      if (type.indexOf('supermarket') > -1) {
        result.push(good);
      }
    }
    this.setData({
      goods: result
    });
  },
  addGoods: function (event) {
    let id = event.currentTarget.id
    let g = this.data.goods.find(item => item.id == id)
    let goodList = wx.getStorageSync('goodList');
    if (goodList) {
      let f = goodList.find(item => item.id == id)
      if (f) {
        return
      } else {
        goodList.push(g)
        wx.setStorageSync('goodList', goodList);
      }
    } else {
      let goods = []
      goods.push(g)
      wx.setStorageSync('goodList', goods);
    }
    wx.showToast({
      title: '添加成功',
      icon: 'success',
      duration: 1000
    });
  },
  detail: function (e) { // 详情
    let id = e.currentTarget.id
    let g = this.data.goods.find(item => item.id == id)
    let list = JSON.stringify(g)
    wx.navigateTo({
      url: '../detail/detail?list=' + list,
    })
  }
})